package cc.lzmsh.service.impl;

import cc.lzmsh.domain.entity.LoginUser;
import cc.lzmsh.domain.entity.User;
import cc.lzmsh.domain.result.Result;
import cc.lzmsh.domain.vo.BlogUserLoginVo;
import cc.lzmsh.domain.vo.UserInfoVo;
import cc.lzmsh.service.BlogLoginService;
import cc.lzmsh.utils.BeanCopyUtils;
import cc.lzmsh.utils.JwtUtil;
import cc.lzmsh.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Author:   msh
 * Date:     2024/9/18 下午2:35
 * Description:
 */

@Service
public class BlogLoginServiceImpl implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Result login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 获取userid，生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // 把用户信息存入redis中
        redisCache.setCacheObject("bloglogin:" + userId, loginUser);

        // 把token和userinfo返回给前端
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo vo = new BlogUserLoginVo(jwt, userInfoVo);
        return Result.success(vo);
    }

    @Override
    public Result logout() {
        // 获取token，解析获取userid
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        // 获取userid
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        // 删除redis中的用户信息
        redisCache.deleteObject("bloglogin:" + userId);
        return Result.success();
    }
}
